<template>
  <div class="app-container">

    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
      <!-- <el-form-item label="创建时间" prop="createTime">
        <el-date-picker v-model="queryParams.createTime" style="width: 240px" value-format="yyyy-MM-dd HH:mm:ss" type="daterange"
                        range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" :default-time="['00:00:00', '23:59:59']" />
      </el-form-item> -->
      <el-form-item label="商品名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入商品名称" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="商品编号" prop="code">
        <el-input v-model="queryParams.code" placeholder="请输入商品编号" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <!-- <el-form-item label="商品分类" prop="type">
        <el-cascader v-model="queryParams.type" :options="options" size="small"></el-cascader>
      </el-form-item>
      <el-form-item label="运费模版id" prop="postalId">
        <el-input v-model="queryParams.postalId" placeholder="请输入运费模版id" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="是否包邮" prop="postage">
        <el-select v-model="queryParams.postage" placeholder="请选择" clearable size="small">
          <el-option label="是" :value="1" />
          <el-option label="否" :value="2" />
        </el-select>
      </el-form-item> -->
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择" clearable size="small">
          <el-option label="上架" :value="1"/>
          <el-option label="下架" :value="2"/>
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="图文详情" prop="imgInfo">
        <el-input v-model="queryParams.imgInfo" placeholder="请输入图文详情" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="规格" prop="specif">
        <el-input v-model="queryParams.specif" placeholder="请输入规格" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="oneHandleAdd">新增普通商品</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="piEditImg">批量修改图片</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="daoruShow = true">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                   :loading="exportLoading">导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 列表 -->
    <el-table ref="tables" v-loading="loading" :data="list" @selection-change="handleSelectionChange">
      <!-- <el-table-column label="id" align="center" prop="id" /> -->
      <!-- <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column> -->
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column label="商品名称" align="center" prop="name"/>
      <el-table-column label="商品编号" align="center" prop="code"/>
      <!--      <el-table-column label="标价" align="center" prop="listPrice" />-->
      <!--      <el-table-column label="售价" align="center" prop="disPrice" />-->
      <el-table-column label="图片" align="center" prop="img">
        <template v-slot="scope">
          <div class="imgbox" v-if="scope.row.img.length !== 0">
            <img class="imgstyle" :src="scope.row.img[scope.row.imgIndex]" alt="">
            <div class="toleftstyle" @click="toleft(scope.$index,scope.row.img.length,scope.row.imgIndex)"><i
              class="el-icon-arrow-left"></i></div>
            <div class="torightstyle" @click="toright(scope.$index,scope.row.img.length,scope.row.imgIndex)"><i
              class="el-icon-arrow-right"></i></div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="商品分类" align="center" prop="type">
        <template v-slot="scope">
          <span>{{ gettype(scope.row.type) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="销售数量" align="center" prop="saleNum"/>
      <el-table-column label="商品价格" align="center" prop="goodsPrice"/>
      <el-table-column label="商品库存" align="center" prop="goodsSize"/>

      <!-- <el-table-column label="运费模版id" align="center" prop="postalId" />
      <el-table-column label="是否包邮" align="center" prop="postage" >
        <template v-slot="scope">
          <span>{{baoyouobj[scope.row.postage]}}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="折扣状态" align="center" prop="isDisGoods">
        <template v-slot="scope">
          <el-tag :type="scope.row.isDisGoods == 1 ? 'success' : 'info'" effect="dark">{{ isDisGoodsObj[scope.row.isDisGoods] }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template v-slot="scope">
          <el-tag :type="scope.row.status == 1 ? 'success' : 'info'" effect="dark">{{ statusobj[scope.row.status] }}
          </el-tag>
        </template>
      </el-table-column>
      <!-- <el-table-column label="商品描述" align="center" prop="content" />
      <el-table-column label="图文详情" align="center" prop="imgInfo" /> -->
      <!-- <el-table-column label="规格" align="center" prop="specif" /> -->
      <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width">
        <template v-slot="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="resetZhe(scope.row)">配置折扣</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="lookCode(scope.row)">查看条形码</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="changeimgSort(scope.row)">描述图片顺序
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>

    <!-- 导入商品 -->
    <el-dialog
      title="导入商品"
      :visible.sync="daoruShow"
      width="30%">
      <div>
        <el-upload
          class="upload-demo"
          drag
          :action="actives"
          :headers="headers"
          :http-request="daorurequest"
          accept=".xlsx, .xls"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">只能上传xlsx/xls文件，且不超过10M，<a style="color:rgb(24,144,255)"
                                                                                     href="https://jockers.oss-cn-beijing.aliyuncs.com/xyx商品导入模板.xls">模板下载</a>
          </div>
        </el-upload>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="daoruShow = false">取 消</el-button>
        <!-- <el-button type="primary" @click="changeimgSortConfirm">确 定</el-button> -->
      </span>
    </el-dialog>
    <!-- 批量修改图片 -->
    <el-dialog
      title="批量修改图片"
      :visible.sync="piliangEditshow"
      @close="piclose"
      width="800px">
      <div class="piliang" v-for="(item,index) in changeTableList" :key="index+'adwad'">
        <h2>{{ item.name }}</h2>
        <el-upload
          class="upload-demo"
          ref="upload"
          :action="actives"
          :headers="headers"
          :http-request="(e)=>piuploadSectionFile(e,index)"
          :on-remove="(a,b)=>pihandleRemove(a,b,index)"
          :file-list="item.imgUrl"
          list-type="picture">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">图片大小不能超过 10 M</div>
        </el-upload>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="piliangEditshow = false">取 消</el-button>
        <el-button type="primary" @click="pichangeimgSortConfirm">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 调整商品描述图片顺序 -->
    <el-dialog
      title="调整商品描述图片顺序"
      :visible.sync="imgSortshow"
      width="700px">
      <div style="display:flex;flex-direction: column;">
        <div style="display:flex;justify-content: center;align-items: center;" v-for="item in imgSortForm.content"
             :key="item.url"><img style="width:300px;height:450px;margin-right:10px;" :src="item.url">
          <el-input v-model="item.urlSort" type="Number" placeholder="请输入顺序"></el-input>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="imgSortshow = false">取 消</el-button>
        <el-button type="primary" @click="changeimgSortConfirm">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="title" :visible.sync="open" width="90%" v-dialogDrag append-to-body>
      <div class="dialog-box">
        <el-form class="box-item queryform" ref="form" :model="form" :rules="rules" label-width="130px">
          <el-form-item label="商品名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入商品名称"/>
          </el-form-item>
          <el-form-item label="商品编号" prop="code">
            <el-input v-model="form.code" placeholder="请输入商品编号"/>
          </el-form-item>
          <el-form-item label="图片" prop="img">
            <el-upload
              class="upload-demo"
              ref="upload"
              :action="actives"
              :headers="headers"
              :before-upload="beforeuploads"
              :http-request="(e)=>uploadSectionFile(e,1)"
              :on-remove="handleRemove"
              :file-list="waifilelist"
              list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">图片大小不能超过 10 M</div>
            </el-upload>
          </el-form-item>
          <el-form-item label="商品分类" prop="type">
            <el-cascader v-model="form.type" placeholder="请选择商品分类" :options="options"></el-cascader>
          </el-form-item>
          <el-form-item label="供应商" prop="supplierId">
            <el-select @change="supplierchange" v-model="form.supplierId" filterable placeholder="请选择">
              <el-option
                v-for="item in gongyingList"
                :key="item.supplierId"
                :label="item.supplierName"
                :value="item.supplierId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="运费模版" prop="postalId">
            <!-- <el-input v-model="form.postalId" placeholder="请输入运费模版id" /> -->
            <el-select @change="postalIdchange" :disabled="isShowpostalIdchange" v-model="form.postalId" filterable
                       placeholder="请选择">
              <el-option
                v-for="item in postalIdoptions"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="是否包邮" prop="postage">
            <el-radio-group v-model="form.postage">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="2">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio :label="1">上架</el-radio>
              <el-radio :label="2">下架</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="商品描述">
            <!-- <editor v-model="form.content" :min-height="192"/> -->
            <el-upload
              class="upload-demo"
              ref="upload"
              :action="actives"
              :headers="headers"
              :http-request="uploadSectionFileimgInfo"
              :on-remove="handleRemoveimgInfo"
              :file-list="filelistimgInfo"
              list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">图片大小不能超过 10 M</div>
            </el-upload>
          </el-form-item>
          <!--          <el-form-item label="图文详情" prop="imgInfo">-->
          <!--            <el-input v-model="form.imgInfo" placeholder="请输入图文详情" />-->
          <!--          </el-form-item>-->
        </el-form>
        <!--  -->
        <el-dialog title="规格" :visible.sync="openspcifshow" width="40%" append-to-body>
          <p style="display:flex;align-items:center;"><span style="width:50px"> 名称：</span>
            <el-input v-model="specifobj.name" placeholder="请输入内容"></el-input>
          </p>
          <p style="display:flex;align-items:center;"><span style="width:50px"> 图片：</span>
            <el-upload
              class="upload-demo"
              ref="upload"
              :action="actives"
              :headers="headers"
              :http-request="uploadSectionFile"
              :before-upload="beforeuploads"
              :on-remove="handleRemove"
              :file-list="filelist"
              :limit="1"
              list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">图片大小不能超过 10 M</div>
            </el-upload>
          </p>

          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="addspecif">确 定</el-button>
            <el-button @click="openspcifshow=false">取 消</el-button>
          </div>
        </el-dialog>

        <!-- 尺码规格表格 -->
        <el-button type="primary" @click="openspcif">新增尺码规格</el-button>
        <el-table :data="form.specif" border style="width: 70%">
          <el-table-column prop="" label="" type="expand" width="30">
            <template v-slot="scope">
              <el-table :data="scope.row.child" border style="width: 100%">
                <el-table-column prop="size" label="尺码">
                  <template v-slot="scop">
                    <div>
                      <el-input v-model="scop.row.size" placeholder="请输入内容"></el-input>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="price" label="价格">
                  <template v-slot="scop">
                    <div>
                      <el-input v-model="scop.row.price" placeholder="请输入内容"></el-input>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="num" label="库存数量">
                  <template v-slot="scop">
                    <div>
                      <el-input v-model="scop.row.num" placeholder="请输入内容"></el-input>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="weight" label="重量">
                  <template v-slot="scop">
                    <div style="display:flex;align-items:center;">
                      <el-input v-model="scop.row.weight" placeholder="请输入内容"></el-input>
                      <span style=" white-space: nowrap;">kg</span>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="" label="操作">
                  <template v-slot="scop">
                    <div>
                      <!-- <el-button v-if="scop.$index === 0" size="mini" type="primary" @click="scope.row.child.push({})">新增</el-button> -->
                      <el-button type="danger" size="mini" @click="scope.row.child.splice(scop.$index,1)">删除
                      </el-button>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="名称"></el-table-column>
          <el-table-column prop="url" label="图片">
            <template v-slot="scope">
              <div>
                <img style="width:50px;height:50px;" :src="scope.row.url" alt="">
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template v-slot="scope">
              <div>
                <el-button type="primary" size="mini" @click="editspcif(scope.row,scope.$index)">编辑</el-button>
                <el-button type="primary" size="mini" @click="addchildList(scope.$index)">添加尺码价格</el-button>
                <el-button type="danger" size="mini" @click="form.specif.splice(scope.$index,1)">删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 商品属性新增弹框 -->
        <el-dialog title="商品属性" :visible.sync="attrShow" width="40%" append-to-body>
          <p style="display:flex;align-items:center;"><span style="width:50px"> 属性名称：</span>
            <el-input v-model="attrChild.name" placeholder="请输入内容"></el-input>
          </p>
          <p style="display:flex;align-items:center;"><span style="width:50px"> 属性内容：</span>
            <el-input v-model="attrChild.content" placeholder="请输入内容"></el-input>
          </p>

          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="addAttr">确 定</el-button>
            <el-button @click="attrShow=false">取 消</el-button>
          </div>
        </el-dialog>

        <!-- 商品属性表格 -->
        <el-button type="primary" @click="openattrShow">新增商品属性</el-button>
        <el-table :data="form.attributes" border style="width: 70%">
          <el-table-column prop="" label="" type="expand" width="30">
          </el-table-column>

          <el-table-column prop="name" label="属性名称"></el-table-column>
          <el-table-column prop="content" label="属性内容"></el-table-column>
          <el-table-column label="操作">
            <template v-slot="scope">
              <div>
                <el-button type="primary" size="mini" @click="editAttr(scope.row,scope.$index)">编辑</el-button>
                <el-button type="danger" size="mini" @click="form.attributes.splice(scope.$index,1)">删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加普通商品 -->
    <el-dialog :title="title" :visible.sync="oneOpen" width="90%" v-dialogDrag append-to-body>
      <div class="dialog-box">
        <el-form class="box-item queryform" ref="form" :model="form" :rules="rules" label-width="130px">
          <el-form-item label="商品名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入商品名称"/>
          </el-form-item>
          <el-form-item label="商品编号" prop="code">
            <el-input v-model="form.code" placeholder="请输入商品编号"/>
          </el-form-item>
          <el-form-item label="图片" prop="img">
            <el-upload
              class="upload-demo"
              ref="upload"
              :action="actives"
              :headers="headers"
              :before-upload="beforeuploads"
              :http-request="(e)=>uploadSectionFile(e,1)"
              :on-remove="handleRemove"
              :file-list="waifilelist"
              list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">图片大小不能超过 10 M</div>
            </el-upload>
          </el-form-item>
          <el-form-item label="商品分类" prop="type">
            <el-cascader v-model="form.type" placeholder="请选择商品分类" :options="options"></el-cascader>
          </el-form-item>
          <el-form-item label="供应商" prop="supplierId">
            <el-select @change="supplierchange" v-model="form.supplierId" filterable placeholder="请选择">
              <el-option
                v-for="item in gongyingList"
                :key="item.supplierId"
                :label="item.supplierName"
                :value="item.supplierId">
              </el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="销售数量" prop="saleNum">
            <el-input v-model="form.saleNum" placeholder="请输入销售数量" />
          </el-form-item> -->
          <el-form-item label="运费模版" prop="postalId">
            <!-- <el-input v-model="form.postalId" placeholder="请输入运费模版id" /> -->
            <el-select @change="postalIdchange" :disabled="isShowpostalIdchange" v-model="form.postalId" filterable
                       placeholder="请选择">
              <el-option
                v-for="item in postalIdoptions"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="标价" prop="listPrice">
            <el-input v-model="form.listPrice" type="Number" placeholder="请输入标价" />
          </el-form-item> -->
          <!--          <el-form-item label="售价" prop="disPrice">-->
          <!--            <el-input v-model="form.disPrice" type="Number" placeholder="请输入售价" />-->
          <!--          </el-form-item>-->
          <el-form-item label="是否包邮" prop="postage">
            <el-radio-group v-model="form.postage">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="2">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio :label="1">上架</el-radio>
              <el-radio :label="2">下架</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="商品描述">
            <!-- <editor v-model="form.content" :min-height="192"/> -->
            <el-upload
              class="upload-demo"
              ref="upload"
              :action="actives"
              :headers="headers"
              :http-request="uploadSectionFileimgInfo"
              :on-remove="handleRemoveimgInfo"
              :file-list="filelistimgInfo"
              list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">图片大小不能超过 10 M</div>
            </el-upload>
          </el-form-item>

          <el-form-item label="sku名称" prop="oneName">
            <el-input v-model="form.oneName" placeholder="请输入sku名称"/>
          </el-form-item>
          <el-form-item label="sku图片">
            <el-upload
              class="upload-demo"
              ref="upload"
              :action="actives"
              :headers="headers"
              :http-request="oneUploadSectionFileimgInfo"
              :on-remove="oneHandleRemoveimgInfo"
              :file-list="oneFilelistimgInfo"
              :limit="1"
              list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">图片大小不能超过 10 M</div>
            </el-upload>
          </el-form-item>
          <el-form-item label="价格" prop="onePrice">
            <el-input v-model="form.onePrice" placeholder="请输入价格"/>
          </el-form-item>
          <el-form-item label="库存数" prop="oneSize">
            <el-input v-model="form.oneSize" placeholder="请输入库存"/>
          </el-form-item>

        </el-form>

        <!-- 商品属性表格 -->
        <el-button type="primary" @click="openattrShow">新增商品属性</el-button>
        <el-table :data="form.attributes" border style="width: 70%">
          <el-table-column prop="" label="" type="expand" width="30">
          </el-table-column>

          <el-table-column prop="name" label="属性名称"></el-table-column>
          <el-table-column prop="content" label="属性内容"></el-table-column>
          <el-table-column label="操作">
            <template v-slot="scope">
              <div>
                <el-button type="primary" size="mini" @click="editAttr(scope.row,scope.$index)">编辑</el-button>
                <el-button type="danger" size="mini" @click="form.attributes.splice(scope.$index,1)">删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="oneSubmitForm">确 定</el-button>
        <el-button @click="oneCancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看条形码 -->
    <el-dialog
      title="查看条形码"
      :visible.sync="codeShow"
      width="30%">
      <div class="codebox">
        <img :src="codeUrl" alt="">
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="codeShow = false">取 消</el-button>
      </span>
    </el-dialog>
    <!-- 配置折扣 -->
    <resetDiscount :outerVisible.sync="resetZheouterVisible" :values.sync="productValue"></resetDiscount>
  </div>
</template>

<script>
import {createGoods, updateGoods, deleteGoods, getGoods, getGoodsPage, exportGoodsExcel} from "@/api/qd/goods";
import Editor from '@/components/Editor';
import resetDiscount from './resetDiscount';
import form from "@/views/bpm/form/index.vue";

export default {
  name: "Goods",
  components: {
    Editor,
    resetDiscount
  },
  data() {
    return {
      actives: process.env.VUE_APP_BASE_API + '/pc/file/upload',
      headers: {Authorization: 'Bearer ' + localStorage.getItem('ACCESS_TOKEN')},
      specifobj: {},
      daoruShow: false, // 导入
      childobj: {},
      filelist: [],
      waifilelist: [], // 最外层的图片数组
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 小程序-商品列表
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 普通商品弹出层
      oneOpen: false,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        createTime: [],
        name: null,
        img: null,
        type: null,
        saleNum: null,
        postalId: null,
        postage: null,
        status: null,
        content: null,
        imgInfo: null,
        specif: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      baoyouobj: {1: '是', 2: '否'},
      statusobj: {1: '上架', 2: '下架'},
      isDisGoodsObj: {1: '启用', 2: '未启用'},
      options: [], // 商品分类详情数据
      openspcifshow: false,
      isedit: null,
      postalIdoptions: [], // 运费模板数据
      filelistimgInfo: [], // 图文详情
      oneFilelistimgInfo: [], // 普通sku图片
      isShowpostalIdchange: true, // 商品模版是否可选
      imgSortshow: false,
      imgSortForm: {}, // 调整商品描述图片顺序数据
      gongyingList: [],
      codeShow: false,
      codeUrl: '',
      piliangEditshow: false, // 批量修改图片
      changeTableList: [], // 选中的表格列表

      //商品属性
      attrShow:false,
      attrChild: {},//属性子集
      attrEdit:false,
      attrIndex:null,
      resetZheouterVisible:false, // 配置折扣弹窗
      productValue:{}, // 配置折扣商品数据
    };
  },
  created() {
    if (this.$route.query.supplierId) this.queryParams.supplierId = this.$route.query.supplierId
    this.getList();
    // 获取其他数据
    this.fenleiList()
  },
  watch: {
    'form.postage': {
      handler() {
        if (this.form.postage == 1) this.isShowpostalIdchange = true
        if (this.form.postage == 2) this.isShowpostalIdchange = false
      }
    }
  },
  methods: {
    resetZhe(row){ // 配置折扣
      this.productValue = row ?? {}
      this.resetZheouterVisible = true
    },
    piEditImg() { // 批量修改按钮
      if (this.changeTableList.length === 0) return this.$message.warning('请先选择数据')
      this.changeTableList.forEach(item => {
        this.$set(item, 'imgUrl', [])
        if (item.img instanceof Array) {
          item.img.forEach(ite => {
            item.imgUrl.push({url: ite})
          })
        }

      })
      this.piliangEditshow = true

    },
    piclose() { // 批量修改图片弹窗关闭事件
      this.$refs.tables.clearSelection()
    },
    pichangeimgSortConfirm() { // 批量修改图片弹窗确认按钮
      this.changeTableList.forEach(item => {
        item.img = []
        if (item.imgUrl instanceof Array) {
          item.imgUrl.forEach(ite => {
            item.img.push(ite.url)
          })
        }
        delete item.imgUrl
      })
      this.$axios({url: '/qd/goods/addGoodsFile', method: 'post', data: {list: this.changeTableList}}).then(res => {
        this.$message.success('修改成功')
        this.getList()
        this.piliangEditshow = false
      })
    },
    handleSelectionChange(e) { // table 选中的值
      this.changeTableList = e
    },
    piuploadSectionFile(val, index) {// 批量修改图片上传
      let file = val.file
      let size = file.size / 1024 / 1024;
      if (size > 10) {
        return this.$message.warning('图片大小不能超过 10 M')
      }
      // 根据后台需求数据格式
      const form = new FormData();
      // 文件对象
      form.append("multipartFile", file);
      // 本例子主要要在请求时添加特定属性，所以要用自己方法覆盖默认的action
      // form.append("clientType", 'xxx');
      // 项目封装的请求方法，下面做简单介绍
      this.$axios({url: '/pc/file/upload', method: 'post', data: form}).then(res => {

        this.changeTableList[index].imgUrl.push({url: res.data})
        this.$message.success('上传成功')
      })
        .catch(() => {
          // xxx
        });
    },
    pihandleRemove(file, fileList, index) {  // 批量修改删除操作
      this.changeTableList[index].imgUrl = fileList
    },
    daorurequest(val, pan) { // 导入
      let file = val.file
      let size = file.size / 1024 / 1024;
      if (size > 10) {
        return this.$message.warning('文件大小不能超过 10 M')
      }
      // 根据后台需求数据格式
      const form = new FormData();
      // 文件对象
      form.append("file", file);
      // 本例子主要要在请求时添加特定属性，所以要用自己方法覆盖默认的action
      // form.append("clientType", 'xxx');
      // 项目封装的请求方法，下面做简单介绍
      this.$axios({url: '/qd/goods/importGoods', method: 'post', data: form}).then(res => {
        this.$message.success('导入成功')
        this.getList()
      })
        .catch(() => {
          // xxx
        });
    },
    lookCode(row) { // 查看条形码
      this.$axios({url: '/qd/goods/getBarCode?id=' + row.id, method: 'get'}).then(res => {
        this.codeUrl = res.data ?? ''
        this.codeShow = true
      })
    },
    changeimgSort(row) { // 调整商品描述图片顺序
      getGoods(row.id).then(res => {
        this.imgSortForm = res.data
        this.imgSortshow = true
      })
    },
    changeimgSortConfirm() { // 调整商品描述图片顺序确认按钮
      this.imgSortForm.content.sort((a, b) => a.urlSort - b.urlSort)
      updateGoods(this.imgSortForm).then(response => {
        this.$modal.msgSuccess("修改成功");
        this.imgSortshow = false
        this.getList();
      });
    },
    fenleiList() {
      // 获取商品分类数据
      this.$axios({url: 'qd/goodsType/getTree', method: 'get'}).then(res => {
        this.options = res.data ?? []
        // 删除第三层级的children
        this.options.forEach(item => {
          item.children.forEach(ite => {
            ite.children.forEach(it => {
              delete it.children
            })
          })
        })
      })
      // 获取运费模板数据
      this.$axios({url: '/qd/logistics-modul/getModelList', method: 'get'}).then(res => {
        this.postalIdoptions = res.data ?? []
      })
      // 获取供应商
      this.$axios({url: '/qd/supplier/getSupList', method: 'get'}).then(res => {
        this.gongyingList = res.data ?? []
      })
    },
    supplierchange(e) {  // 供应商change事件
      this.form.supplierName = this.gongyingList.filter(item => item.supplierId === e)[0].supplierName
    },
    toleft(index, imglength, iindex) {  // 图片向右
      if (iindex === 0) return this.list[index].imgIndex = imglength - 1 ?? 0
      this.list[index].imgIndex -= 1
    },
    toright(index, imglength, iindex) {  // 图片向左
      if (imglength - 1 === iindex) return this.list[index].imgIndex = 0
      this.list[index].imgIndex += 1
    },
    postalIdchange(e) { // 运费模板选中事件
      let arr = this.postalIdoptions.filter(item => item.id === e)
      this.form.postalName = arr[0].name
    },
    openspcif() {  // 新增规格按钮
      this.specifobj = {}
      this.filelist = []
      this.openspcifshow = true
    },
    openattrShow(){
      this.attrChild={}
      this.attrShow=true
    },
    editspcif(row, index) {
      this.specifobj = {...row}
      this.filelist = [{url: row.url}]
      // 是否是编辑
      this.isedit = index
      this.openspcifshow = true
    },
    addspecif() { // 新增规格弹窗确定
      if (this.isedit !== null) {
        // this.form.specif[this.isedit] = {...this.specifobj}
        this.$set(this.form.specif,this.isedit,JSON.parse(JSON.stringify(this.specifobj)))
        // 清空上传换成图片
        this.filelist = []
        this.openspcifshow = false
        this.isedit = null
        return
      }
      if (!this.specifobj.name) return this.$message.warning('名称不能为空')
      if (!this.specifobj.url) return this.$message.warning('图片不能为空')
      if (typeof this.form.specif === 'object') {
        this.form.specif.push({...this.specifobj})
      } else {
        this.form.specif = []
        this.form.specif.push({...this.specifobj})
      }
      // 给child自动赋值一个
      // let index = this.form.specif.length -1
      // this.form.specif[index].child=[{}]
      this.specifobj = {}
      // 清空上传换成图片
      this.filelist = []
      this.openspcifshow = false
    },
    //添加商品属性
    addAttr(){
      if (!this.attrEdit){
        if (typeof form.attributes === 'undefined'){
          this.form.attributes=[];
        }
        this.form.attributes.push(JSON.parse(JSON.stringify(this.attrChild)))
        this.attrShow=false
        return
      }else {
        if (!this.attrChild.name) return this.$message.warning('名称不能为空')
        if (!this.attrChild.content) return this.$message.warning('内容不能为空')
        // this.form.attributes[this.attrIndex]=this.attrChild
        this.$set(this.form.attributes,this.attrIndex,JSON.parse(JSON.stringify(this.attrChild)))
        this.attrChild={}
        this.attrShow=false
        this.attrEdit=false
      }
    },
    editAttr(row, index) {
      this.attrChild = {...row}
      // 是否是编辑
      this.attrEdit = true
      this.attrShow = true
      this.attrIndex=index
    },
    addchildList(index) {  // 添加child
      if (typeof this.form.specif[index].child === 'object') {
        this.form.specif[index].child.push({})
      } else {
        this.$set(this.form.specif[index], 'child', [])
        this.form.specif[index].child.push({})
      }
    },
    // 图片上传之前
    beforeuploads() {
      // this.$refs.upload.forEach((item,index)=>{
      //   this.$refs.upload[index].clearFiles();
      // })
      // this.$refs.upload.clearFiles(); //上传成功之后清除历史记录
    },
    uploadSectionFile(val, pan) {  // 上传图片请求
      let file = val.file
      let size = file.size / 1024 / 1024;
      if (size > 10) {
        return this.$message.warning('图片大小不能超过 10 M')
      }
      // 根据后台需求数据格式
      const form = new FormData();
      // 文件对象
      form.append("multipartFile", file);
      // 本例子主要要在请求时添加特定属性，所以要用自己方法覆盖默认的action
      // form.append("clientType", 'xxx');
      // 项目封装的请求方法，下面做简单介绍
      this.$axios({url: '/pc/file/upload', method: 'post', data: form}).then(res => {

        // 如果是最外层的就等于1
        if (pan === 1) {
          this.waifilelist.push({url: res.data})
        } else {
          this.specifobj.url = res.data
          this.filelist = [{url: res.data}]
        }
        this.$message.success('上传成功')
      })
        .catch(() => {
          // xxx
        });
    },
    // 移除图片时
    handleRemove(file, fileList) {
      this.filelist = fileList
      this.waifilelist = fileList
    },
    uploadSectionFileimgInfo(val) {
      let file = val.file
      let size = file.size / 1024 / 1024;
      if (size > 10) {
        return this.$message.warning('图片大小不能超过 10 M')
      }
      // 根据后台需求数据格式
      const form = new FormData();
      // 文件对象
      form.append("multipartFile", file);
      // 本例子主要要在请求时添加特定属性，所以要用自己方法覆盖默认的action
      // form.append("clientType", 'xxx');
      // 项目封装的请求方法，下面做简单介绍
      this.$axios({url: '/pc/file/upload', method: 'post', data: form}).then(res => {
        // 获取图片的宽高
        let reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = (e) => {
          const img = e.target.result;
          const image = new Image()
          image.src = img

          image.onload = _ => {
            let width = image.width
            let height = image.height
            // 做需要的操作了
            this.filelistimgInfo.push({url: res.data, size: width / height})
          }
        }
        this.$message.success('上传成功')
      })
    },
    //普通商品上传sku的图片
    oneUploadSectionFileimgInfo(val) {
      let file = val.file
      let size = file.size / 1024 / 1024;
      if (size > 10) {
        return this.$message.warning('图片大小不能超过 10 M')
      }
      // 根据后台需求数据格式
      const form = new FormData();
      // 文件对象
      form.append("multipartFile", file);
      // 本例子主要要在请求时添加特定属性，所以要用自己方法覆盖默认的action
      // form.append("clientType", 'xxx');
      // 项目封装的请求方法，下面做简单介绍
      this.$axios({url: '/pc/file/upload', method: 'post', data: form}).then(res => {

        this.oneFilelistimgInfo.push({url: res.data})
        this.form.oneImg = res.data
        this.$message.success('上传成功')
      })
    },
    handleRemoveimgInfo(file, fileList) { // 移除图片时
      this.filelistimgInfo = fileList
    },
    oneHandleRemoveimgInfo(file, fileList) { // 移除图片时
      this.oneFilelistimgInfo = fileList
    },
    gettype(str) {  //根据商品类型id获取值
      let a = '', b = '', c = ''
      if (str) {
        let arr = str.split(',')
        this.options.forEach(item => {
          if (item.value === Number(arr[0])) {
            a = item.label ?? ''
            item.children.forEach(ite => {
              if (ite.value === Number(arr[1])) {
                b = item.label ?? ''
                ite.children.forEach(it => {
                  if (it.value === Number(arr[2])) {
                    c = it.label ?? ''
                  }
                })
              }
            })
          }
        })
      }
      return a + ' / ' + b + ' / ' + c
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 执行查询
      getGoodsPage(this.queryParams).then(response => {
        this.list = response.data.list ?? [];
        this.list.forEach(item => {
          this.$set(item, 'imgIndex', 0)
        })
        this.total = response.data.total;
        this.loading = false;
      });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 普通商品取消按钮 */
    oneCancel() {
      this.oneOpen = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        img: undefined,
        type: undefined,
        saleNum: undefined,
        postalId: undefined,
        postage: undefined,
        status: undefined,
        content: undefined,
        imgInfo: undefined,
        specif: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      if (this.$route.query.supplierId) this.queryParams.supplierId = undefined
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.filelist = []
      this.waifilelist = []
      this.filelistimgInfo = []
      // this.$refs.upload.forEach((item,index)=>{
      //   this.$refs.upload[index].clearFiles();
      // })
      this.form.breakSign = 1
      this.open = true;
      this.title = "添加商品";
    },
    /** 新增普通商品 */
    oneHandleAdd() {
      this.reset();
      this.filelist = []
      this.waifilelist = []
      this.filelistimgInfo = []
      // this.$refs.upload.forEach((item,index)=>{
      //   this.$refs.upload[index].clearFiles();
      // })
      this.form.breakSign = 1
      this.oneOpen = true;
      this.title = "添加普通商品";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.waifilelist = []
      const id = row.id;
      getGoods(id).then(response => {
        this.form = response.data;
        if (this.form.type) {
          this.form.type = response.data.type.split(',').map(Number)
        }
        // 判断img是否类型正确，然后给上传图片的数组赋值
        if (typeof response.data.img === 'object') {
          response.data.img.forEach(item => {
            this.waifilelist.push({url: item})
          })

        }
        if (typeof response.data.type === 'object') {
          this.form.type.forEach(item => {
            item = parseInt(item)
          })
        }
        // 赋值商品描述图片
        this.filelistimgInfo = []
        if (response.data.content instanceof Array) {
          response.data.content.map(item => this.filelistimgInfo.push({...item}))
          // this.filelistimgInfo = [{url:response.data.content}]
        }
        this.open = true;
        this.title = "修改小程序-商品";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return;
        }
        if (this.form.postage == 2) {
          if (!this.form.postalId) return this.$message.warning('请选择运费模板')
        }
        // 判断规格里面的size 是否为空 ， 为空不能添加
        if (this.form.specif instanceof Array) {
          if (this.form.specif.length === 0) return this.$message.warning('请完整填写规格,可能有漏写情况')
          const a = this.form.specif.some(item => {
            if (item.child instanceof Array) return item.child.length === 0
            return true
          })
          if (a) return this.$message.warning('请完整填写规格,可能有漏写情况')
        } else {
          return this.$message.warning('请完整填写规格,可能有漏写情况')
        }
        this.form.img = []
        this.waifilelist.forEach(item => {
          this.form.img.push(item.url)
        })
        // 赋值商品描述图片
        this.form.content = []
        this.filelistimgInfo.forEach((item, index) => {
          this.form.content.push({...item})
        })
        if (this.form.type instanceof Array) {
          this.form.type = this.form.type.join(',')
        }
        // 修改的提交
        if (this.form.id != null) {
          updateGoods(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
          return;
        }
        // 添加的提交
        createGoods(this.form).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      });
    },
    /** 普通商品提交按钮 */
    oneSubmitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return;
        }
        if (this.form.postage == 2) {
          if (!this.form.postalId) return this.$message.warning('请选择运费模板')
        }
        if (typeof(this.form.oneName) == "undefined")
          return this.$message.warning('请选择sku名称')
        if (typeof(this.form.oneImg) == "undefined")
          return this.$message.warning('请选择sku图片')
        if (typeof(this.form.onePrice) == "undefined")
           return this.$message.warning('请选择视频价格')
        if (typeof(this.form.oneSize) == "undefined")
           return this.$message.warning('请选择库存')


        this.form.img = []
        this.waifilelist.forEach(item => {
          this.form.img.push(item.url)
        })
        // 赋值商品描述图片
        this.form.content = []
        this.filelistimgInfo.forEach((item, index) => {
          this.form.content.push({...item})
        })
        if (this.form.type instanceof Array) {
          this.form.type = this.form.type.join(',')
        }
        // 修改的提交
        if (this.form.id != null) {
          updateGoods(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
          return;
        }
        // 添加的提交
        createGoods(this.form).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$modal.confirm('是否确认删除?').then(function () {
        return deleteGoods(id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      let params = {...this.queryParams};
      params.pageNo = undefined;
      params.pageSize = undefined;
      this.$modal.confirm('是否确认导出所有小程序-商品数据项?').then(() => {
        this.exportLoading = true;
        return exportGoodsExcel(params);
      }).then(response => {
        this.$download.excel(response, '小程序-商品.xls');
        this.exportLoading = false;
      }).catch(() => {
      });
    },
  }
};
</script>
<style lang="scss" scoped>
@import "../../styles/imgstyle.scss";

.codebox {
  display: flex;
  justify-content: center;
  align-items: center;
}

.piliang {
  margin-top: 20px;
}
</style>
